<?php
class DownloadImg
{
//    const BASE_URL = "http://file.api.weixin.qq.com/cgi-bin/media/get";
    const BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin/media/get";

    protected static $instance;
    public static function getInstance(){
        $className = get_called_class();
        if(!isset(self::$instance)){
            self::$instance = new $className();
        }
        return self::$instance;
    }

    private function getApiURL($access_token,$media_id)
    {
        $querys = array(
            'access_token'=>$access_token,
            'media_id'=>$media_id
        );
        $q = http_build_query($querys);

        return self::BASE_URL."?".$q;
    }

    public function getMedia($access_token,$media_id)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->getApiURL($access_token, $media_id));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        $http_info = curl_getinfo($ch);
        curl_close($ch);
        $media_info = array_merge(array('header'=>$http_info),array('body'=>$output));
        return $media_info;
    }

    public function downloadToLocal($f,$c)
    {
        $l = fopen($f, 'w');
        if(false !== $l){
            if(false !== fwrite($l, $c)){
                fclose($l);
                return true;
            }
            else{
                return false;
            }
        }
        else{
            return false;
        }
    }
}